<template>
  <div style="padding: 0 auto">
    <el-steps
      :active="active"
      finish-status="success"
      style="width: 80%; margin: 0 auto"
    >
      <el-step title="添加用户"></el-step>
      <el-step title="选择职位"></el-step>
      <el-step title="完善细节"></el-step>
    </el-steps>

    <!-- <el-button style="margin-top: 12px" @click="next">下一步</el-button> -->

    <!-- 添加用户 -->
    <div v-show="active == 0">
      <el-form
        style="width: 40%; margin: 0 auto"
        ref="form"
        :model="user"
        label-width="80px"
        :rules="rules1"
      >
        <el-form-item label="状态">
          <el-select v-model="user.status" placeholder="请选择用户类型">
            <el-option label="管理员" value="1"></el-option>
            <el-option label="普通用户" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="user.username"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="user.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onUserSubmit">手动添加</el-button>
          <el-button type="success" @click="dialogVisible = true"
            >批量导入</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <el-dialog
      title="请选择要导入的excel文件"
      :visible.sync="dialogVisible"
      width="21%"
    >
      <el-button
        type="primary"
        style="margin-bottom: 10px"
        @click="getTemplate"
      >
        获取模板
      </el-button>
      <span class="getTemplate">注：批量添加的员工的账号为手机号，密码为123456</span>
      <el-upload
        class="upload-demo"
        drag
        action=""
        multiple
        :on-preview="handlePreview"
        :on-change="handleChangeFile"
        :on-remove="handleRemove"
        :file-list="fileList"
        :auto-upload="false"
        :on-exceed="handleExceedFileLimit"
        :limit="1"
        :show-file-list="true"
        accept=".xls, .xlsx"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__text">只能上传xls/xlsx文件</div>
        <!-- <div class="el-upload__tip" slot="tip">只能上传xls/xlsx文件</div> -->
      </el-upload>
      <el-button size="normal" type="success" @click="submitUpload"
        >确定</el-button
      >
    </el-dialog>
    <!-- 选择职位 -->
    <div v-show="active == 1">
      <el-form
        style="width: 40%; margin: 0 auto"
        ref="form"
        :model="employee"
        label-width="80px"
      >
        <el-form-item label="部门">
          <el-select v-model="employee.deptId" placeholder="请选择用户所属部门">
            <el-option
              v-for="item in deptData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="岗位">
          <el-select v-model="employee.jobId" placeholder="请选择用户所属岗位">
            <el-option
              v-for="item in jobData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="基础工资">
          <el-input v-model="employee.baseSalary"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onEmployeeSubmit">确定</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 完善细节 -->
    <div v-show="active == 2">
      <el-form
        style="margin: 0 0 0 250px"
        ref="form"
        :model="employeeDetails"
        label-width="80px"
        :rules="rules3"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="employeeDetails.name"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="手机" prop="phone">
              <el-input v-model="employeeDetails.phone"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="employeeDetails.sex" placeholder="性别">
                <el-option label="男" value="1"></el-option>
                <el-option label="女" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="民族">
              <el-input v-model="employeeDetails.race"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="学历">
              <el-input v-model="employeeDetails.education"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮箱">
              <el-input v-model="employeeDetails.email"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="身份证">
              <el-input v-model="employeeDetails.cardNum"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电话">
              <el-input v-model="employeeDetails.tel"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="政治面貌">
              <el-input v-model="employeeDetails.party"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="qq号码">
              <el-input v-model="employeeDetails.qqNum"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="联系地址">
              <el-input v-model="employeeDetails.address"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮编">
              <el-input v-model="employeeDetails.postCode"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="爱好">
              <el-input v-model="employeeDetails.hobby"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="专业">
              <el-input v-model="employeeDetails.speciality"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row></el-row>

        <el-form-item label="备注" style="width: 1000px">
          <el-input type="textarea" v-model="employeeDetails.remake"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onDetailsSubmit"
            >立即添加</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <!-- 完成添加 -->
    <div v-show="active == 3" class="congratulations">
      <div>恭喜！公司又多了一名得力干将！</div>
    </div>
  </div>
</template>

<script>
export default {
  name: "AddUser",
  data() {
    var checkUsername = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("用户名不能为空"));
      } else {
        // 调用后端api
        this.$request
          .post("securityUser/queryExist", { username: value })
          .then((res) => {
            if (!res.data.obj) {
              callback();
              console.log();
            } else {
              callback(new Error("用户名已被注册！"));
            }
          });
      }
    };
    return {
      dialogVisible: false,
      fileList: [],
      active: 0,
      user: {
        status: "",
        username: "",
        password: "",
      },
      jobData: "", //本公司的职位信息
      deptData: "", //部门信息
      employee: {
        userId: "",
        deptId: "",
        jobId: "",
        baseSalary: "",
      },
      employeeDetails: {
        employeeId: "",
        name: "",
        sex: "",
        phone: "",
        cardNum: "",
        education: "",
        address: "",
        postCode: "",
        tel: "",
        qqNum: "",
        email: "",
        party: "",
        race: "",
        speciality: "",
        hobby: "",
        remake: "",
      },
      rules1: {
        username: [
          {
            validator: checkUsername,
            trigger: "blur",
          },
        ],
      },
      rules3: {
        name: [{ required: true, message: "员工姓名", trigger: "blur" }],
        sex: [{ required: true, message: "选择员工性别", trigger: "blur" }],
        phone: [
          { required: true, message: "请输入员工的手机号码", trigger: "blur" },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: "手机号码格式不正确",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    next() {
      if (this.active++ > 2) this.active = 0;
    },
    //检测用户名是否存在接口
    queryExist(value) {
      this.$request
        .post("securityUser/queryExist", { username: value })
        .then((res) => {
          return res.data.obj;
        });
    },
    onUserSubmit() {
      if (
        this.user.username != "" &&
        this.user.class != "" &&
        this.user.password != ""
      ) {
        this.next();
      } else {
        this.$message.error("请输入完整再次尝试！");
      }
    },
    onEmployeeSubmit() {
      if (
        this.employee.deptId != "" &&
        this.employee.jobId != "" &&
        this.employee.baseSalary != ""
      ) {
        this.next();
      } else {
        this.$message.error("请输入完整再次尝试！");
      }
    },
    onDetailsSubmit() {
      let reg = /^1[3456789]\d{9}$/;
      if (reg.test(this.employeeDetails.phone)) {
        this.$request
          .post("securityUser/insert", {
            username: this.user.username,
            password: this.user.password,
            status: this.user.status,
          })
          .then((res) => {
            this.employee.userId = res.data.obj.id;
            this.$request
              .post("employee/insert", {
                userId: this.employee.userId,
                deptId: this.employee.deptId,
                jobId: this.employee.jobId,
                baseSalary: this.employee.baseSalary,
              })
              .then((res) => {
                this.employeeDetails.employeeId = res.data.obj.id;
                this.employee.userId = "";
                const details = this.employeeDetails;
                this.$request
                  .post("employee-details/insert", details)
                  .then((res) => {
                    if (res.data.obj) {
                      this.$message.success("添加成功！");
                      //成功过后置空所有对象的值
                      Object.keys(this.user).forEach((key) => {
                        this.user[key] = "";
                      });
                      Object.keys(this.employee).forEach((key) => {
                        this.employee[key] = "";
                      });
                      Object.keys(this.employeeDetails).forEach((key) => {
                        this.employeeDetails[key] = "";
                      });

                      this.next();

                      window.setTimeout(() => {
                        this.next();
                      }, 1500);
                    } else {
                      this.$message.warning("添加失败");
                    }
                  });
              });
          });
      } else {
        this.$message.warning("请输入正确手机号");
      }
    },
    //获取所有部门信息
    getAllDept() {
      this.$request.get("dept/queryAll").then((res) => {
        // console.log(res);
        if (res.data.obj != null) {
          this.deptData = res.data.obj;
          console.log(this.deptData);
        } else {
          this.$message.error("信息获取失败");
        }
      });
    },
    //获取所有的职位信息
    getAllJob() {
      this.$request.get("job/queryAll").then((res) => {
        if (res.data.obj != null) {
          this.jobData = res.data.obj;
          // console.log(this.jobData);
        } else {
          this.$message.error("信息获取失败");
        }
      });
    },
    //获取模板文件
    getTemplate() {
      window.open(window.origin + "/api/download/添加员工模板.xlsx");
    },
    //确认上传
    submitUpload() {
      let formData = new FormData();
      formData.append("file", this.fileList[0].raw);
      this.$request.post("/employee/insertByExcel", formData).then((res) => {
        if (res.data.obj == true) {
          this.$message.success("添加成功");
          this.dialogVisible = false;
          this.fileList = [];
        } else {
          this.$message.error("添加失败");
        }
        // console.log('res', res.data.obj)
      });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    /**
     * 文件超出个数限制
     */
    handleExceedFileLimit() {
      this.$message.warning("只能上传一个文件");
    },

    /**
     * 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
     * @param file 当前文件
     * @param fileList 文件列表
     */
    handleChangeFile(file, fileList) {
      //将文件信息存入对应的fileList
      console.log("file", file);
      this.fileList.push(file);
      console.log("文件列表", this.fileList);
    },

    /**
     * 文件列表移除文件时的钩子
     * @param file 移除的图片
     * @param fileList 图片列表
     */
    handleRemoveFile(file, fileList) {
      //文件移除
      this.fileList = [];
      console.log("文件列表", this.fileList);
    },

    /**
     * 删除文件之前的钩子，参数为上传的文件和文件列表，
     * 若返回 false 或者返回 Promise 且被 reject，则停止删除。
     * @param file 移除的图片
     * @param fileList 图片列表
     */
    beforeRemoveFile(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
  },
  mounted() {
    this.getAllDept();
    this.getAllJob();
  },
};
</script>

<style scoped>
.el-input {
  width: 400px;
}
upload-demo {
  margin: 0 auto;
}
.getTemplate {
  position: absolute;
  bottom: 5px;
  right: 10px;
}
.el-dialog {
  padding: 0 auto;
}
.congratulations {
  margin: auto;
  padding: auto;
  text-align: center;
}
</style>
